/**
 *  学习目标：Todos 案例
 *    1. 函数组件
 *    2. 拆分函数组件(头部，主体，底部)
 *    3. 初始化列表数据，并渲染到主体组件中
 *    4. 主体 - 根据 id 删除数据
 *    5. 主体 - 根据 id 更新完成状态
 *    6. 底部 - 删除已完成任务
 *    7. 底部 - 计算剩余任务数量
 *    8. 底部 - 高亮切换效果
 *    9. 底部 - 切换显示列表(全部显示/未完成/已完成)
 *    10. 头部 - 受控组件，获取数据，按回车键，新增待办任务
 *    11. 主体 - 计算全选状态，切换全选状态
 *    12. 数据初始化 - 获取本地存储数据
 *    13. 数据更新时 - 设置本地存储数据
 */
import React, { useEffect, useState } from 'react'
import { useDispatch, useSelector } from 'react-redux'
import { TodoState } from './store'
import { addTodo, changeAll, changeDoneById, changeType, clearAllDone, delById } from './store/action/todos'
import './styles/base.css'
import './styles/index.css'

export default function App() {
  const { list, type } = useSelector((state: TodoState) => state)
  // 数据更新时 - 设置本地存储数据
  useEffect(() => {
    localStorage.setItem('todo-list', JSON.stringify(list))
    localStorage.setItem('todo-type', type)
  }, [list, type])
  return (
    <section className='todoapp'>
      {/* 头部 */}
      <Header />
      {/* 主体 */}
      <Main />
      {/* 底部 */}
      <Footer />
    </section>
  )
}

function Header() {
  // 用于收集表单数据用的
  const [content, setContent] = useState('')
  const dispatch = useDispatch()

  // 用户键盘弹起
  const onKeyUp = (e: React.KeyboardEvent<HTMLInputElement>) => {
    // console.log(e.key)
    // 如果按回车键
    if (e.key === 'Enter') {
      // 非空判断
      if (content.trim() === '') return alert('请输入内容...')
      // console.log('通知父组件添加待办事项')
      dispatch(addTodo({ id: Date.now(), content: content, done: false }))
      // 发布成功后清空
      setContent('')
    } else if (e.key === 'Escape') {
      // 按 Esc 键清空输入
      setContent('')
    }
  }
  return (
    <header className='header'>
      <h1>todos</h1>
      <input
        className='new-todo'
        value={content}
        onChange={(e) => setContent(e.target.value)}
        onKeyUp={(e) => onKeyUp(e)}
        placeholder='What needs to be done?'
        autoFocus
      />
    </header>
  )
}

function Main() {
  const { list, type } = useSelector((state: TodoState) => state)
  const dispatch = useDispatch()
  let showList = list
  if (type === 'active') {
    showList = list.filter(v => !v.done)
  } else if (type === 'completed') {
    showList = list.filter(v => v.done)
  }

  // 计算全选状态
  const checkAll = list.length !== 0 && list.every((v) => v.done)

  return (
    <section className='main'><input
      className='toggle-all'
      checked={checkAll}
      onChange={() => dispatch(changeAll(!checkAll))}
      type='checkbox'
      id='toggle-all'
    />
      <label htmlFor='toggle-all'>Mark all as complete</label>
      <ul className='todo-list'>
        {showList.map(item => <li key={item.id} className={item.done ? 'completed' : ''}>
          <div className='view'>
            <input className='toggle' checked={item.done} onChange={() => dispatch(changeDoneById(item.id))} type='checkbox' />
            <label>{item.content}</label>
            <button className='destroy' onClick={() => dispatch(delById(item.id))}></button>
          </div>
          <input className='edit' />
        </li>)}
      </ul>
    </section>
  )
}

function Footer() {
  const dispatch = useDispatch()
  const { list, type } = useSelector((state: TodoState) => state)
  const leftCount = list.filter(v => !v.done).length
  return (
    <footer className='footer'>
      <span className='todo-count'>
        <strong>{leftCount}</strong> item left
      </span>
      <ul className='filters'>
        <li>
          <a onClick={() => dispatch(changeType('all'))} className={type === 'all' ? 'selected' : ''} href='#/'>
            All
          </a>
        </li>
        <li>
          <a onClick={() => dispatch(changeType('active'))} className={type === 'active' ? 'selected' : ''} href='#/active'>
            Active
          </a>
        </li>
        <li>
          <a onClick={() => dispatch(changeType('completed'))} className={type === 'completed' ? 'selected' : ''} href='#/completed'>
            Completed
          </a>
        </li>
      </ul>
      <button onClick={() => dispatch(clearAllDone())} className='clear-completed'>Clear completed</button>
    </footer>
  )
}
